package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    public static final Integer IS_NOT_DEFAULT = 0;

    public static final Integer IS_DEFAULT = 1;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBook> list() {
        List<AddressBook> list = addressBookMapper.listByUserId(BaseContext.getCurrentId());
        return list;
    }

    @Override
    public void save(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setCreateTime(LocalDateTime.now());
        addressBook.setIsDefault(IS_NOT_DEFAULT);       // 非默认地址
        addressBookMapper.insert(addressBook);
    }

    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);
    }

    @Override
    public void editInfo(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    @Override
    public void deleteById(Long id) {
        addressBookMapper.delete(id);
    }

    @Override
    public void setDefault(AddressBook addressBook) {
        // 1.将当前表中该用户的所有地址的状态设置为非默认
        addressBook.setIsDefault(IS_NOT_DEFAULT);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateDefaultByUserId(addressBook);

        // 2.设置默认地址
        addressBook.setIsDefault(IS_DEFAULT);
        addressBookMapper.update(addressBook);
    }

    @Override
    public AddressBook getDefault() {
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .isDefault(IS_DEFAULT)
                .build();
        addressBook = addressBookMapper.getDefault(addressBook);
        return addressBook;
    }
}
